package com.yunmang.activity.ordermanager;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.utils.Utils;
import com.yunmang.R;
import com.yunmang.activity.kaipiaoActivity;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.ParameterEntity.OrderLookBean;
import com.yunmang.utils.ChangeRmb;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.DateUtil;
import com.yunmang.utils.FormatUtils;
import com.yunmang.utils.SharedPreferencesUtils;
import com.yunmang.view.MessagePrintBox;
import com.yunmang.view.StatusPrintBox;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

import HPRTAndroidSDK.HPRTPrinterHelper;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import zpSDK.zpSDK.zpSDK;

/**
 * Created by Administrator on 2017/5/25.
 */
public class OrderBudaDialog extends Activity {

    @InjectView(R.id.tv_tiaoma)
    TextView tvTiaoma;
    @InjectView(R.id.biaoqian_dialog_top)
    LinearLayout biaoqianDialogTop;
    @InjectView(R.id.start)
    EditText start;
    @InjectView(R.id.end)
    EditText end;
    @InjectView(R.id.biaoqian_shuliang)
    EditText biaoqianShuliang;
    @InjectView(R.id.biaoqian_dialog_middle)
    LinearLayout biaoqianDialogMiddle;
    @InjectView(R.id.biaoqian_queding_dialog)
    TextView biaoqianQuedingDialog;
    @InjectView(R.id.biaoqian_quxiao_dialog)
    TextView biaoqianQuxiaoDialog;
    @InjectView(R.id.biaoqian_dialog_layout)
    RelativeLayout biaoqianDialogLayout;
    private String type;
    StatusPrintBox statusBox;
    private MessagePrintBox megBox;
    public static BluetoothAdapter myBluetoothAdapter;
    private Activity act;
    private  OrderLookBean.ModelBean.ItemsBean itemsBean;
    private Handler handler;
    private String SelectedTagAddress;
    private String printerstyle;//打印机类型
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderbuda);
        ButterKnife.inject(this);
        megBox = new MessagePrintBox(this);
        act=this;
        itemsBean= AppConstant.itemsBean;
        type = getIntent().getStringExtra("type");
        if (type.equals("0")) {
            tvTiaoma.setText("是否补打运单");
            biaoqianDialogMiddle.setVisibility(View.GONE);
        } else {
            tvTiaoma.setText("是否补打条码");
            biaoqianDialogMiddle.setVisibility(View.VISIBLE);
        }
        printerstyle=SharedPreferencesUtils.getParameter(this,"selectedTagName");

        handler= new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        int ss=Integer.parseInt(CommonUtils.getTextViewValue(start));
                        int en=Integer.parseInt(CommonUtils.getTextViewValue(end));
                        Tag(SelectedTagAddress,0,ss,en);
                        zpSDK.zp_close();
                        finish();
                        break;
                }
            }
        };
    }

    @OnClick({R.id.biaoqian_queding_dialog, R.id.biaoqian_quxiao_dialog})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.biaoqian_queding_dialog:
                CommonUtils.hideSoftInput(this);
                biaoqianQuedingDialog.setEnabled(false);
                if(type.equals("0")){
                    biaoqianShuliang.setText("1");
                    if(printerstyle.equals("HM-T300")){

                    if(!HPRTPrinterHelper.IsOpened()){
                        tryconnect(1,1,false);
                    }else{
                        printOrder();
                    }
                }else{
                    if (0 == SharedPreferencesUtils.getParameter(this, "SelectedPrintMac").length()) {
                        Toast.makeText(this, "请选择票据打印机",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    statusBox = new StatusPrintBox(this,biaoqianQuedingDialog);
                    final String SelectedTagAddress = SharedPreferencesUtils.getParameter(this, "SelectedPrintMac");
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            if (OpenPrinter(SharedPreferencesUtils.getParameter(act, "SelectedPrintMac"))) {
                                if (!"".equals(biaoqianShuliang.getText().toString().trim())) {
                                    for(int i=0;i<1;i++){
                                        Print_new(SelectedTagAddress, "",i);
                                    }
                                }
                            }
                            zpSDK.zp_close();
                            finish();
                        }
                    });
                }

                }else{

                    if ("".equals(CommonUtils.getTextViewValue(start))) {
                        Toast.makeText(act, "请填写开始范围",Toast.LENGTH_SHORT).show();
                        biaoqianQuedingDialog.setEnabled(true);
                        return;
                    }
                    if("".equals(CommonUtils.getTextViewValue(end))){
                        Toast.makeText(act, "请填写结束范围", Toast.LENGTH_SHORT).show();
                        biaoqianQuedingDialog.setEnabled(true);
                        return;
                    }
                    if(Integer.parseInt(CommonUtils.getTextViewValue(start))==0){
                        Toast.makeText(act, "标签范围必须大于0", Toast.LENGTH_SHORT).show();
                        biaoqianQuedingDialog.setEnabled(true);
                        return;
                    }

                    if (0 == SharedPreferencesUtils.getParameter(act, "SelectedTagMac").length()) {
                        Toast.makeText(act, "请选择标签打印机",Toast.LENGTH_SHORT).show();
                        biaoqianQuedingDialog.setEnabled(true);
                        return;
                    }

                    if(printerstyle.equals("XT4131A")){
                        statusBox = new StatusPrintBox(act, biaoqianQuedingDialog);
                        SelectedTagAddress = SharedPreferencesUtils.getParameter(act, "SelectedTagMac");

                        //这步操作应该放在线程中
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                if (OpenPrinter(SharedPreferencesUtils.getParameter(act, "SelectedTagMac"))) {
                                    biaoqianQuedingDialog.setEnabled(true);
                                    handler.sendEmptyMessage(1);//成功
                                }
                            }
                        });
                    }else if(printerstyle.equals("HM-T300")){
                        int ss=Integer.parseInt(CommonUtils.getTextViewValue(start));
                        int en=Integer.parseInt(CommonUtils.getTextViewValue(end));
                        if(!HPRTPrinterHelper.IsOpened()){
                            tryconnect(ss,en,true);
                        }else{
                            hmprint(ss,en);
                        }
                    }
                }
                break;
            case R.id.biaoqian_quxiao_dialog:
                finish();
                break;
        }
    }

    public boolean OpenPrinter(String BDAddress) {
        if (BDAddress == "" || BDAddress == null) {
            Toast.makeText(this, "没有选择打印机", Toast.LENGTH_LONG).show();
            return false;
        }
        BluetoothDevice myDevice;
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (myBluetoothAdapter == null) {
            Toast.makeText(this, "读取蓝牙设备错误", Toast.LENGTH_LONG).show();
            return false;
        }
        myDevice = myBluetoothAdapter.getRemoteDevice(BDAddress);
        if (myDevice == null) {
            Toast.makeText(this, "读取蓝牙设备错误", Toast.LENGTH_LONG).show();
            return false;
        }
        if (zpSDK.zp_open(myBluetoothAdapter, myDevice) == false) {
            Toast.makeText(this, "与蓝牙设备建立连接失败", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    public void Print_new(String BDAddress, String doubleString, int i) {
        statusBox.Show("正在打印小票...");
        if (!zpSDK.zp_page_create(80, 150)) {
            Toast.makeText(this, "创建打印页面失败", Toast.LENGTH_LONG).show();
            statusBox.Close();
            return;
        }
        zpSDK.TextPosWinStyle = false;

        zpSDK.zp_page_clear();
        zpSDK.zp_draw_text_ex(26, 8, "", "Arial", 6, 0,
                false, false, false);
        zpSDK.zp_draw_barcode(18, 11, itemsBean.getHdbh(),
                zpSDK.BARCODE_TYPE.BARCODE_CODE128, 10, 3, 0); // /////////////////////下面全是横线///////////////////////////////////
        zpSDK.zp_draw_text_ex(1, 25 + 5, "货号: " + itemsBean.getHdbh(),
                "Arial", 4, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 25 + 5 + 5, "发货单号：" + itemsBean.getHdbh(),
                "Arial", 4, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 25 + 5 + 5 + 5, "发货日期：" + itemsBean.getBillDate(),
                "Arial", 4, 0, false, false, false);

        zpSDK.zp_draw_line(1, 41 + 1, 80, 41 + 1, 2); // 第一条线
        zpSDK.zp_draw_text_ex(1, 46, "起站：" +itemsBean.getStartOrgName(), "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(40, 46, "到站：" + itemsBean.getEndOrgName(), "Arial", 3, 0, false,
                false, false);
        zpSDK.zp_draw_text_ex(1, 49.5, "客户卡号：" + "", "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 49.5, "中转至：" + "", "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 53, "发货人：" + itemsBean.getShipper(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 53, itemsBean.getShipperPhone(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 56.5, "收货人：" + itemsBean.getConsignee(), "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(40, 56.5, itemsBean.getConsigneePhone(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_line(1, 58 + 1, 80, 58 + 1, 2); // 第二条线
        zpSDK.zp_draw_text_ex(1, 58 + 5, "货物名称：" + itemsBean.getGoodsName(), "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(40, 58 + 5, "包装：" +"", "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 61.5 + 5, "数量：" + itemsBean.getNumbers(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 61.5 + 5, "运费：" + itemsBean.getTransportCost(), "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 65 + 5, "送货费：" + itemsBean.getDeliveryCost(), "Arial", 3,
                0, false, false, false);
        if ("0".equals("") && !"".equals("")) {
            zpSDK.zp_draw_text_ex(40, 65 + 5, "中转费：" + "另计", "Arial", 3, 0,
                    false, false, false);
        } else {
            zpSDK.zp_draw_text_ex(40, 65 + 5, "中转费：" + itemsBean.getTransferCost(),
                    "Arial", 3, 0, false, false, false);
        }
        zpSDK.zp_draw_text_ex(1, 72 + 5 - 3.5, "备注：" + "", "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_line(1, 78.5 + 1 - 3.5, 80, 78.5 + 1 - 3.5, 2); // 第三条线
        zpSDK.zp_draw_text_ex(1, 78.5 + 5 - 3.5,
                "付款方式：" +itemsBean.getBalanceMethod() , "Arial", 3, 0, false, false,
                false);
        zpSDK.zp_draw_text_ex(40, 78.5 + 5 - 3.5, "提货方式：" +"",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(
                1,
                82 + 5 - 3.5,
                "运费合计：￥"
                        + String.valueOf(Double.valueOf(itemsBean.getTransportCost()+"")
                        + Double.valueOf(itemsBean.getTransferCost())
                        + Double.valueOf(itemsBean.getDeliveryCost())), "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(
                40,
                82 + 5 - 3.5,
                ChangeRmb.toRMB(Double.valueOf(itemsBean.getTransportCost())
                        + Double.valueOf(itemsBean.getTransferCost())
                        + Double.valueOf(itemsBean.getDeliveryCost())), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 87 + 5 - 3.5, "货款: ￥" + itemsBean.getGoodsCost(),
                "Arial", 5, 0, false, false, false);
        if ("".equals(ChangeRmb.toRMB(Double.valueOf(itemsBean.getGoodsCost())))) {
            zpSDK.zp_draw_text_ex(1, 92 + 5 - 3.5, "货款大写: 零元整", "Arial", 5, 0,
                    false, false, false);
        } else {
            zpSDK.zp_draw_text_ex(1, 92 + 5 - 3.5,
                    "货款大写: " + ChangeRmb.toRMB(Double.valueOf(itemsBean.getGoodsCost())),
                    "Arial", 5, 0, false, false, false);
        }
        zpSDK.zp_draw_line(1, 98 + 1 - 3.5, 80, 98 + 1 - 3.5, 2); // 第四条线
        zpSDK.zp_draw_text_ex(1, 98 + 5 - 3.5, "开票人：" + AppConstant.orgInfo.getName() , "Arial", 3, 0, false, false, false);


        zpSDK.zp_draw_text_ex(1, 112 + 5, "到站电话："+"", "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 112 + 5+3.5, "查货微信：" + "yuanhang56", "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 115.5 + 5+3.5, "查货网址："
                        + "http://www.yuanhang56.com", "Arial", 3, 0, false, false,
                false);
        zpSDK.zp_page_print(false);
        zpSDK.zp_printer_status_detect();
        zpSDK.zp_goto_mark_right(15);
        if (zpSDK.zp_printer_status_get(8000) != 0) {
            Toast.makeText(this, "打印失败", Toast.LENGTH_LONG).show();
        }
        zpSDK.zp_page_free();
        statusBox.Close();
    }


    public void Tag(String BDAddress, int num, int start, int tagNum) {
        statusBox.Show("正在打印标签...");

        if (!zpSDK.zp_page_create(80,48)) {
            Toast.makeText(this, "创建打印页面失败", Toast.LENGTH_LONG).show();
            statusBox.Close();
            return;
        }
        for (int i =start; i <=tagNum; i++) {
            draw_tag(i);
            zpSDK.zp_page_print(false);
            zpSDK.zp_goto_mark_label(44);
            zpSDK.zp_printer_status_detect();
            if (zpSDK.zp_printer_status_get(8000) != 0) {
                if (megBox.showDialog(zpSDK.ErrorMessage, "打印失败") == 1) {
                    i--;
                    continue;
                } else {
                    statusBox.Close();
                    zpSDK.zp_page_free();
                    break;
                }
            }
        }// for
        zpSDK.zp_page_free();
        statusBox.Close();
    }

    public void draw_tag(int num){
        String sub=String.valueOf(num);
        if(sub.length()==1){
            sub="000"+sub;
        }else if(sub.length()==2){
            sub="00"+sub;
        }else if(sub.length()==3){
            sub="0"+sub;
        }else{
            sub=String.valueOf(sub);
        }

        String subHdbh=itemsBean.getHdbh()+sub;
        zpSDK.zp_page_clear();
        zpSDK.zp_draw_rect(0, 0, 70,47, 3);
        zpSDK.zp_draw_text_ex(2,3,"博特利华", "Arial", 3, 0,false, false, false);
        zpSDK.zp_draw_text_ex(45,3,itemsBean.getBillDate().substring(0,10),"Arial",3,0,false, false, false);
        zpSDK.zp_draw_text_ex(16,3,itemsBean.getHdbh(),"Arial",3,0,false, false, false);
        zpSDK.zp_draw_line(0,4.5,70,4.5,3);
        zpSDK.zp_draw_rect(0,4.5,18,47,3);
        zpSDK.zp_draw_barcode(12,10,subHdbh, zpSDK.BARCODE_TYPE.BARCODE_CODE128, 10,2,270);
        zpSDK.zp_draw_text_ex(14,12,subHdbh, "Arial", 3.5, 90,false, false, false);
        zpSDK.zp_draw_text_ex(20,10,"","Arial",4, 0, false, false, false);
        zpSDK.zp_draw_text_ex(50,10,itemsBean.getStartOrgName(),"Arial",3, 0, false, false, false);
        zpSDK.zp_draw_line(18,12,70,12,3);
        zpSDK.zp_draw_text_ex(30,17,itemsBean.getConsignee(),"Arial",4.5,0,false, false, false);
        zpSDK.zp_draw_rect(60,12,70,19,3);
        zpSDK.zp_draw_text_ex(62.5,17,"", "Arial", 4.5,0,false, false, false);
        zpSDK.zp_draw_line(18,19,70,19,3);
        zpSDK.zp_draw_text_ex(21,24,itemsBean.getEndOrgName(), "Arial",5,0,false, false, false);
        zpSDK.zp_draw_text_ex(51,24,"", "Arial",5,0,false, false, false);
        zpSDK.zp_draw_line(18,40,70,40,3);
        zpSDK.zp_draw_text_ex(21,38,itemsBean.getNumbers()+"件","Arial",5,0,false, false, false);
        zpSDK.zp_draw_text_ex(51,38,"","Arial",5.5,0,false, false, false);
        zpSDK.zp_draw_text_ex(25,45,itemsBean.getWeight()+"Kg","Arial",4,0,false, false, false);
        zpSDK.zp_draw_text_ex(48,45,itemsBean.getCubage()+"m³","Arial",4,0,false, false, false);
    }

    /**
     * 执行打印票据
     */
    private void printOrder() {
        try {
            HPRTPrinterHelper.printAreaSize("0", "200","600","450","1");
            HPRTPrinterHelper.LanguageEncode="GBK";
            HPRTPrinterHelper.Align(HPRTPrinterHelper.LEFT);
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","150","5", AppConstant.companyName+"运单");
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","0","180","55", itemsBean.getHdbh());
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","1","10","85",AppConstant.orgInfo.getName()+"-"+itemsBean.getEndOrgName()+"  "+itemsBean.getNumbers()+"件");
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","1","10","135", "发货人:"+itemsBean.getShipper()+"  "+itemsBean.getShipperPhone());
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","1","10","185", "收货人:"+itemsBean.getConsignee()+"  "+itemsBean.getConsigneePhone());
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","1","10","230", "运费:"+itemsBean.getTransportCost()+"  送货费："+itemsBean.getDeliveryCost()+"  中转费："+itemsBean.getTransferCost());
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","1","10","280", "货款:"+itemsBean.getGoodsCost());
            HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","1","10","330","时间："+DateUtil.date2string(new Date(),DateUtil.YYYY_MM_DD_HH_MM_SS)+"  "+itemsBean.getTakeMethod()+"  "+itemsBean.getBalanceMethod());
            HPRTPrinterHelper.Form();
//            HPRTPrinterHelper.Print();
            HPRTPrinterHelper.PrintData("POPRINT\r\n");
            biaoqianQuedingDialog.setEnabled(true);
        } catch (Exception e) {
            e.printStackTrace();
            biaoqianQuedingDialog.setEnabled(true);
        }
    }

    /**
     * 执行打印功能
     * @param end2
     * @param start2
     */
    private void hmprint(int start2, int end2) {
        for(int i=start2;i<=end2;i++){
            try {
                printStandard();
//                HPRTPrinterHelper.printAreaSize("0", "200","600","450","1");
//                HPRTPrinterHelper.LanguageEncode="GBK";
//                HPRTPrinterHelper.Align(HPRTPrinterHelper.LEFT);
//                HPRTPrinterHelper.Barcode(HPRTPrinterHelper.BARCODE,HPRTPrinterHelper.code128,"2","1","65","40","40", true,"7","0", "5",itemsBean.getHdbh()+FormatUtils.generate(String.valueOf(i)));
//                HPRTPrinterHelper.Line("10","135","600","135", "2");
//                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","10","150",AppConstant.orgInfo.getName()+"-"+itemsBean.getEndOrgName());
//                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","20","218", "货名:"+itemsBean.getGoodsName());
//                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","20","298", "收货人:"+itemsBean.getConsignee());
//                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","315","230","");
//                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","20","380", DateUtil.date2string(new Date(),DateUtil.YYYY_MM_DD_HH_MM_SS));
//                HPRTPrinterHelper.Form();
////                HPRTPrinterHelper.Print();
//                HPRTPrinterHelper.PrintData("POPRINT\r\n");
            } catch (Exception e) {
                e.printStackTrace();
                biaoqianQuedingDialog.setEnabled(true);
            }
            biaoqianQuedingDialog.setEnabled(true);
        }
    }


    private void printStandard(){
        HPRTPrinterHelper.printAreaSize("0", "200","600","450","1");
        HPRTPrinterHelper.LanguageEncode="GBK";
        HPRTPrinterHelper.Align(HPRTPrinterHelper.LEFT);
        HPRTPrinterHelper.Box("2","2","600","342","2");
        HPRTPrinterHelper.Line("2","102","600","102", "2");

        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","100","15",AppConstant.orgInfo.getName()+"-"+itemsBean.getEndOrgName());
        HPRTPrinterHelper.Box("2","102","85","302","2");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT270,"9","3","70","108","小明");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","0","90","108","运单号:"+itemsBean.getHdbh());
        HPRTPrinterHelper.Line("85","142","600","142", "2");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","0","90","148","货名:"+itemsBean.getGoodsName()+"  件数:"+itemsBean.getNumbers()+"  包装:"+itemsBean.getPack());
        HPRTPrinterHelper.Line("85","182","600","182", "2");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","0","90","188","运费:"+itemsBean.getTransferCost()+"  送货费:"+itemsBean.getDeliveryCost()+"  中转费:"+itemsBean.getTransferCost());
        HPRTPrinterHelper.Line("85","222","600","222", "2");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","0","90","228","货款:"+itemsBean.getGoodsCost());
        HPRTPrinterHelper.Line("85","262","400","262", "2");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","420","240",10+"/"+itemsBean.getNumbers());

        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"8","0","90","268","日期:"+DateUtil.date2string(new Date(),DateUtil.YYYY_MM_DD_HH_MM_SS));
        HPRTPrinterHelper.Line("85","302","600","302", "2");

        HPRTPrinterHelper.Barcode(HPRTPrinterHelper.BARCODE,HPRTPrinterHelper.code128,"2","1","65","8","348", true,"7","0", "5",itemsBean.getHdbh());
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT,"9","3","350","350","华顺快运");
        HPRTPrinterHelper.Form();
        HPRTPrinterHelper.Print();
    }
    /**
     * 重新尝试连接
     * @param end2
     * @param start2
     */
    private void tryconnect(int start2, int end2,boolean isPrintTag) {

        boolean hasConnected=false;
        hasConnected= ConnectDevice();
        if (hasConnected){
            DisConnect();
        }

        if(hasConnected){
            Toast.makeText(this, "连接成功",Toast.LENGTH_SHORT).show();
            kaipiaoActivity.HPRTPrinter=new HPRTPrinterHelper(this,"HM-T300");
            try {
                if(HPRTPrinterHelper.PortOpen("Bluetooth,"+SharedPreferencesUtils.getParameter(this,"SelectedTagMac"))==0){
                    if(isPrintTag){
                        hmprint(start2,end2);
                    }else{
                        printOrder();
                    }
                }
            } catch (Exception e) {
                biaoqianQuedingDialog.setEnabled(true);
                e.printStackTrace();
            }
        }else{
            Toast.makeText(this, "连接失败",Toast.LENGTH_SHORT).show();
            biaoqianQuedingDialog.setEnabled(true);
        }
    }

    private boolean ConnectDevice(){
        boolean bRet=false;
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        myBluetoothAdapter.cancelDiscovery();
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        try
        {
            // 4.0.3版本 经测试，高版本兼容低版本
            mmDevice = myBluetoothAdapter.getRemoteDevice(SharedPreferencesUtils.getParameter(this,"SelectedTagMac"));
            if(Build.VERSION.SDK_INT < 15)
            {
                mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
            }
            else
            {
                mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
            }
            myBluetoothAdapter.cancelDiscovery();
            Thread.sleep(100);
            if(myBluetoothAdapter.isDiscovering())
            {
                int iCnt=0;
                while (iCnt<5)
                {
                    Thread.sleep(100);
                    iCnt++;
                    if(myBluetoothAdapter.cancelDiscovery())
                    {
                        break;
                    }
                }
            }
            mmSocket.connect();
        }
        catch (Exception e)
        {
            try
            {
                Method m;
                m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
                if(myBluetoothAdapter.isDiscovering())
                {
                    int iCnt=0;
                    while (iCnt<5)
                    {
                        Thread.sleep(100);
                        iCnt++;
                        if(myBluetoothAdapter.cancelDiscovery())
                        {
                            break;
                        }
                    }
                }
                mmSocket.connect();
            }
            catch (Exception e1)
            {
                Log.d("PRTLIB", (new StringBuilder("BTO_ConnectDevice --> create ")).append(e1.getMessage()).toString());
                return false;
            }
        }

        try
        {
            bRet=GetIOInterface();
            return bRet;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    private boolean GetIOInterface(){
        Log.d("PRTLIB", "BTO_GetIOInterface...");
        try
        {
            mmInStream = mmSocket.getInputStream();
            mmOutStream = mmSocket.getOutputStream();
        }
        catch(IOException e)
        {
            Log.d("PRTLIB", (new StringBuilder("BTO_GetIOInterface ")).append(e.getMessage()).toString());
            return false;
        }
        return true;
    }
    private InputStream mmInStream;
    private OutputStream mmOutStream;
    private BluetoothDevice mmDevice;
    private BluetoothSocket mmSocket;
    private boolean DisConnect(){
        boolean bRet = true;
        try
        {
            Thread.sleep(500);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        try
        {
            if(mmInStream!=null)
            {
                mmInStream.close();
                mmInStream=null;
            }
            if(mmOutStream!=null)
            {
                mmOutStream.close();
                mmOutStream=null;
            }
            if(mmSocket!=null)
            {
                mmSocket.close();
                mmSocket=null;
            }
        }
        catch (IOException e)
        {
            System.out.println((new StringBuilder("BTO_ConnectDevice close ")).append(e.getMessage()).toString());
            bRet = false;
        }
        return bRet;
    }
}
